package com.cloudpivot.receivales.ding.scenegroup.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cloudpivot.receivales.ding.scenegroup.domain.DingUpdateFileReqDTO;
import com.cloudpivot.receivales.ding.scenegroup.domain.DingUpdateFileRspDTO;
import com.cloudpivot.receivales.ding.scenegroup.domain.DriveSpacesDTO;
import com.cloudpivot.receivales.ding.scenegroup.service.DriveSpacesService;
import com.cloudpivot.receivales.ding.basic.service.DingBasicService;
import com.cloudpivot.receivales.ding.basic.service.impl.HttpAPIServiceForDing;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiMediaUploadRequest;
import com.dingtalk.api.response.OapiMediaUploadResponse;
import com.taobao.api.ApiException;
import com.taobao.api.FileItem;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@Slf4j
public class DriveSpacesServiceImpl implements DriveSpacesService {

    @Autowired
    private DingBasicService dingBasicService;
    @Autowired
    private HttpAPIServiceForDing httpAPIServiceForDing;
    /**
     * 创建 订盘空间
     * @return
     */
    @Override
    public String createDriveSpaces(DriveSpacesDTO entity) {
        String url = "https://api.dingtalk.com/v1.0/drive/spaces";
        String access_token=dingBasicService.getToken("dinggroup");

        try {
            String ret=httpAPIServiceForDing.doPostDing(url, JSONObject.toJSONString(entity), access_token);
            JSONObject rsp = JSONObject.parseObject(ret);
            log.info("创建的订盘空间：{}" + rsp.toJSONString());
            return null;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public OapiMediaUploadResponse dingMediaUpload(DingUpdateFileReqDTO entity) {
        if (Objects.isNull(entity.getBytes()) || StringUtils.isBlank(entity.getName())) {
            return null;
        }
        String access_token=dingBasicService.getToken("dinggroup");
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/media/upload");
        FileItem item = new FileItem(entity.getName(),entity.getBytes());

        OapiMediaUploadRequest req = new OapiMediaUploadRequest();
        req.setType(entity.getType());
        req.setMedia(item);
        try {
            OapiMediaUploadResponse rsp = client.execute(req, access_token);
            return rsp;
        } catch (ApiException e) {
            e.printStackTrace();
            return null;
        }

    }
}
